package com.jtjrenren.android.taxi.driver.core.dutyon;

import android.animation.ObjectAnimator;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Message;
import android.support.v7.app.NotificationCompat;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.LinearInterpolator;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.jtjrenren.android.taxi.driver.Constants;
import com.jtjrenren.android.taxi.driver.base.MvpActivity;
import com.jtjrenren.android.taxi.driver.bean.OrderDesc;
import com.jtjrenren.android.taxi.driver.bean.OrderQD;
import com.jtjrenren.android.taxi.driver.bean.api.ApiYYD;
import com.jtjrenren.android.taxi.driver.core.adapter.JdListAdapter;
import com.jtjrenren.android.taxi.driver.core.adapter.YydAdapter;
import com.jtjrenren.android.taxi.driver.core.order.details.OrderDetailsActivity;
import com.jtjrenren.android.taxi.driver.R;

import com.jtjrenren.android.taxi.driver.core.other.AppMoreActivity;
import com.library.utils.LogUtil;
import com.library.weiget.DividerItemDecoration;
import com.library.weiget.SpaceItemDecoration;
import com.jtjrenren.android.taxi.driver.utils.IntentUtils;
import com.jtjrenren.android.taxi.driver.utils.UIHelper;
import com.library.utils.StringUtils;
import com.library.utils.DensityUtils;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by Administrator on 2016/7/12.
 */
public class WorkDutyOnActivity extends MvpActivity<DutyOnPresenter> implements DutyOnView {
    public static final int WHAT_REFRESH_LIST = 1001;
    //上班相关
    @BindView(R.id.onduty_ssoryy)
    Button bt_change;
    @BindView(R.id.onduty_qd)
    Button bt_qd;
    @BindView(R.id.onduty_xb)
    Button bt_xb;
    @BindView(R.id.onduty_rote)
    ImageView iv_rote;
    @BindView(R.id.dutyon_fm)
    FrameLayout rl_contents;

    //
    @BindView(R.id.onduty_order_countcon)
    LinearLayout ll_countcon;

    @BindView(R.id.onduty_qdcount)
    TextView tv_qdcount;
    @BindView(R.id.onduty_yydcount)
    TextView tv_yydcount;
    @BindView(R.id.ll_income_money)
    TextView tv_income;


    RecyclerView yydListView;
    private PopupWindow yydWin;
    private YydAdapter yydAdapter;


    //订单相关
    private TextView tv_desc, tv_start, tv_end, tv_tip;
    private ImageView iv_type, iv_close;

    private ObjectAnimator jdAnimator;
    private PopupWindow orderWin;
    private int jgPostion; //
    private RecyclerView cy_dlist;
    private JdListAdapter qdAdapter;

    private boolean showYYD = false;
    private TextView tv_bz;

    @Override
    public int getLayoutID() {
        return R.layout.aty_work_duty_on;
    }

    @Override
    protected void handMsg(Message msg) {
        LogUtil.log("dutyon", "current_method--->handMsg");
        super.handMsg(msg);
        int what = msg.what;
        if (what == WHAT_REFRESH_LIST) {
            presenter.refreshQDList();
            handler.sendEmptyMessageDelayed(WHAT_REFRESH_LIST, 2 * 1000);
        }
    }

    @Override
    public void initM() {
        LogUtil.log("dutyon", "current_method--->initM");
        initHandler();
        presenter.init();
        presenter.getNotFinishOrder();
    }

    @Override
    protected void onResume() {
        LogUtil.log("dutyon", "current_method--->onResume");
        super.onResume();
        presenter.getRefreshYYD();
        startRoteAnim();
    }

    @Override
    protected void onPause() {
        LogUtil.log("dutyon", "current_method--->onPause");
        super.onPause();
        stopRoteAnim();
    }

    @Override
    protected void onDestroy() {
        LogUtil.log("dutyon", "current_method--->onDestroy");

        super.onDestroy();
        stopCheckQdList();
        presenter.destory();
        presenter = null;
        stopRoteAnim();
        jdAnimator = null;

    }

    private void startRoteAnim() {
        LogUtil.log("dutyon", "current_method--->startRoteAnim");
        iv_rote.setVisibility(View.VISIBLE);
        if (jdAnimator == null) {
            jdAnimator = ObjectAnimator.ofFloat(iv_rote, "rotation", 0f, 360f);
            jdAnimator.setDuration(1000).setRepeatCount(-1);
            jdAnimator.setInterpolator(new LinearInterpolator());
        }
        jdAnimator.start();
    }

    private void stopRoteAnim() {
        LogUtil.log("dutyon", "current_method--->stopRoteAnim");
        if (jdAnimator != null)
            jdAnimator.cancel();
        iv_rote.setVisibility(View.GONE);
    }

    @Override
    public void hideOrderWin() {
        LogUtil.log("dutyon", "current_method--->hideOrderWin");
        if (orderWin != null && orderWin.isShowing())
            orderWin.dismiss();
    }

    @Override
    public void qdSuccess(String orderID) {
        LogUtil.log("dutyon", "current_method--->qdSuccess");
        startActivity(OrderDetailsActivity.getDiyIntent(this, orderID));
    }

    @Override
    public void showPayResult(String desc) {
        LogUtil.log("dutyon", "current_method--->showPayResult");
        startActivity(OrderDetailsActivity.getDiyIntent(this, desc));
    }

    @Override
    public void finishAty() {
        LogUtil.log("dutyon", "current_method--->finishAty");
        finish();
    }

    @Override
    public void showXBView() {
        IntentUtils.goMainActivity(this);
        finish();
    }

    @Override
    public void showLoginView() {
        IntentUtils.goLoginPage(this);
        finish();
    }

    @Override
    public void showWaittingDialog(String desc) {
        LogUtil.log("dutyon", "current_method--->showWaittingDialog");
        showProDialog(null, desc, false);
    }

    @Override
    public void dissWaittingDialog() {
        LogUtil.log("dutyon", "current_method--->dissWaittingDialog");
        disProDialog();
    }


    @Override
    public void startCheckQdList() {
        LogUtil.log("dutyon", "current_method--->startCheckQdList");
        handler.sendEmptyMessage(WHAT_REFRESH_LIST);
    }

    @Override
    public void stopCheckQdList() {
        LogUtil.log("dutyon", "current_method--->stopCheckQdList");
        handler.removeMessages(WHAT_REFRESH_LIST);
    }

    @Override
    public void refreshYyd(List<ApiYYD> list) {
        LogUtil.log("dutyon", "current_method--->refreshYyd");
        if (showYYD) {
            showYYD(list);
        }
    }

    @Override
    public void refreshYYDCount(int count) {
        LogUtil.log("dutyon", "current_method--->refreshYYDCount");
        tv_yydcount.setText(count + "");
    }

    @Override
    public void refreshSr(String desc) {
        LogUtil.log("dutyon", "current_method--->refreshSr");
        tv_income.setText(desc);
    }

    @Override
    public void showTip(String desc) {
        Toast.makeText(this, desc, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void moveToFont(String desc) {
        LogUtil.log("order", "接单运行到前台去");
        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this);

        mBuilder.setAutoCancel(true)//点击后让通知将消失
                .setPriority(Notification.PRIORITY_DEFAULT)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE | Notification.DEFAULT_LIGHTS)
                .setContentTitle("您有新订单")
                .setContentText(desc)
                .setTicker("您有新订单");

        //点击的意图ACTION是跳转到Intent
        Intent resultIntent = new Intent(this, WorkDutyOnActivity.class);
        resultIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        mBuilder.setContentIntent(pendingIntent);

        NotificationManager mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        mNotificationManager.notify(0, mBuilder.build());
    }

    @Override
    protected void onStop() {
        super.onStop();
        LogUtil.log("dutyon", "程序 onStop");
    }

    @OnClick(R.id.onduty_ssoryy)
    public void changeJD() {
        LogUtil.log("dutyon", "current_method--->changeJD");
        presenter.changeQdType();
    }

    @OnClick(R.id.onduty_qd)
    public void qD() {
        LogUtil.log("dutyon", "current_method--->qD");
        presenter.qd();
    }

    @OnClick(R.id.onduty_xb)
    public void xB() {
        LogUtil.log("dutyon", "current_method--->xB");
        presenter.xB();
    }

    @Override
    public DutyOnPresenterImpl createPresenter() {
        LogUtil.log("dutyon", "current_method--->createPresenter");
        return new DutyOnPresenterImpl(this);
    }


    @Override
    public void refreshQdType(String desc) {
        LogUtil.log("dutyon", "current_method--->refreshQdType");
        bt_change.setText(desc);
    }

    @Override
    public void rereshQdStatus(String desc) {
        LogUtil.log("dutyon", "current_method--->rereshQdStatus");
        bt_qd.setText(desc);
    }

    @Override
    public void refreshOrderList() {
        LogUtil.log("dutyon", "current_method--->refreshOrderList");
        if (qdAdapter != null)
            qdAdapter.notifyDataSetChanged();
    }

    @Override
    public void refreshOrderView(int type, String date, OrderDesc orderDesc) {
        LogUtil.log("dutyon", "current_method--->refreshOrderView");
        if (orderWin == null)
            createOrderWin();

        if (!orderWin.isShowing())
            orderWin.showAtLocation(bt_qd, Gravity.TOP, 0, jgPostion);

        tv_desc.setText(orderDesc.getDT());
        tv_start.setText(orderDesc.getFA());
        tv_end.setText(orderDesc.getTA());

        if (!StringUtils.isEmpty(orderDesc.getSF())) {
            tv_tip.setVisibility(View.VISIBLE);
            tv_tip.setText(orderDesc.getSF());
        } else
            tv_tip.setVisibility(View.GONE);

        tv_bz.setText(StringUtils.isEmpty(orderDesc.getMe()) ? "" : orderDesc.getMe());

        if (type == Constants.TYPE_ORDER_YY) {
            iv_type.setImageResource(R.mipmap.n_def_yuyue);
            tv_desc.setText(date);
        } else
            iv_type.setImageResource(R.mipmap.n_def_shishi);
    }

    @Override
    public void refreshQdDjs(String process) {
        LogUtil.log("dutyon", "current_method--->refreshQdDjs");
        bt_qd.setText("抢单\n" + process + getString(R.string.miao));
    }


    private void createOrderWin() {
        LogUtil.log("dutyon", "current_method--->createOrderWin");
        int[] startLocations = new int[2];
        rl_contents.getLocationOnScreen(startLocations);

        int[] endLocations = new int[2];
        bt_qd.getLocationOnScreen(endLocations);

        int width = rl_contents.getWidth() - DensityUtils.sp2px(this, 30);
        int height = endLocations[1] - startLocations[1] - 10;

        jgPostion = startLocations[1] + 10;

        LayoutInflater layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View orderView = layoutInflater.inflate(R.layout.include_order_jk2, null);

        initOrderViews(orderView);

        orderWin = new PopupWindow(orderView, width, height);
        orderWin.setOutsideTouchable(true);
    }

    private void initOrderViews(View orderView) {
        LogUtil.log("dutyon", "current_method--->initOrderViews");
        tv_desc = (TextView) orderView.findViewById(R.id.order_jy_desc);
        tv_start = (TextView) orderView.findViewById(R.id.order_jy_start);
        tv_end = (TextView) orderView.findViewById(R.id.order_jy_end);
        tv_tip = (TextView) orderView.findViewById(R.id.order_jy_tip);
        iv_close = (ImageView) orderView.findViewById(R.id.order_jy_close);
        iv_type = (ImageView) orderView.findViewById(R.id.order_jy_type);
        cy_dlist = (RecyclerView) orderView.findViewById(R.id.order_jy_list);
        tv_bz = (TextView) orderView.findViewById(R.id.order_jy_bz);

        UIHelper.initVritalReclyView(this, cy_dlist);
        cy_dlist.addItemDecoration(new SpaceItemDecoration(0, 0, 5, 0));

        qdAdapter = new JdListAdapter(this);
        qdAdapter.setList(presenter.getQrderList());
        cy_dlist.setAdapter(qdAdapter);

        iv_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                presenter.closeCurOrder();
            }
        });

        qdAdapter.setClickListener(new JdListAdapter.clickListener() {
            @Override
            public void onItemClick(OrderQD qd) {
                presenter.refreshCurrOrder(qd);
            }
        });
    }

    @OnClick(R.id.title_right)
    public void showMore() {
        LogUtil.log("dutyon", "current_method--->showMore");
        startActivity(new Intent(this, AppMoreActivity.class));
    }

    @OnClick(R.id.onduty_yyd)
    public void clickShowYYD() {
        LogUtil.log("dutyon", "current_method--->clickShowYYD");
        showYYD = true;
        presenter.getRefreshYYD();
    }

    @OnClick(R.id.ll_income)
    public void clickShowIncome() {
        LogUtil.log("dutyon", "current_method--->clickShowIncome");
        IntentUtils.goWallectPage(this);
    }

    @OnClick(R.id.onduty_order_countcon)
    public void clickShowOrderHistory() {
        LogUtil.log("dutyon", "current_method--->clickShowOrderHistory");
        IntentUtils.goOrderHistoryPage(this);
    }


    //展示预约单的列表
    private void showYYD(List<ApiYYD> apiYYDs) {
        LogUtil.log("dutyon", "current_method--->showYYD");
        showYYD = false;
        if (yydWin == null) {
            LayoutInflater layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            View yydView = layoutInflater.inflate(R.layout.include_order_yyds, null);
            yydListView = (RecyclerView) yydView.findViewById(R.id.yyds_list);
            UIHelper.initVritalReclyView(this, yydListView);
            yydListView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL_LIST));
            yydWin = new PopupWindow(yydView, ll_countcon.getWidth(), DensityUtils.dip2px(this, 200));
            yydWin.setFocusable(true);
            yydWin.setOutsideTouchable(true);
            yydWin.setBackgroundDrawable(new ColorDrawable(0x00000000));
        }

        if (yydAdapter == null) {
            yydAdapter = new YydAdapter(this);
            yydListView.setAdapter(yydAdapter);
            yydAdapter.setListener(new YydAdapter.ItemClick() {
                @Override
                public void onItemClick(ApiYYD order) {
                    startActivity(OrderDetailsActivity.getDiyIntent(WorkDutyOnActivity.this, order.getID()));
                }
            });
        }

        yydAdapter.replace(apiYYDs);

        yydWin.showAsDropDown(ll_countcon);
    }
}
